﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using Abp.UI;
using AVIS.OutBound.Infrastructure;
using AVIS.OutBound.Orders;
using AVIS.OutBound.Orders.Cache;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.ThirdOrders
{
    /// <summary>
    /// 游友订单（现在修改为漫游包Wifi订单）的领域服务
    /// </summary>
    public class YouYouOrderManager : DomainService, IYouYouOrderManager
    {
        #region 构造函数
        private static string Url_youyou = ConfigurationManager.AppSettings["Url_youyou"];
        private static string Apikey_youyou = ConfigurationManager.AppSettings["Apikey_youyou"];
        private readonly IRepository<YouYouOrder> _orderRepository;
        private readonly IOrderRepository _avisOrderRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IObjectMapper _objectMapper;
        //private readonly IAbpWebApiClient _abpWebApiClient;

        public YouYouOrderManager(
            IRepository<YouYouOrder> orderRepository,
            ICacheManager cacheManager,
            IObjectMapper objectMapper,
            IOrderRepository avisOrderRepository)
        {
            _orderRepository = orderRepository;
            _cacheManager = cacheManager;
            _objectMapper = objectMapper;
            _avisOrderRepository = avisOrderRepository;
        }
        #endregion

        /// <summary>
        /// 判断是否存在指定ID的游友订单
        /// </summary>
        /// <returns></returns>
        public bool IsExist(int youyouOrderID)
        {
            if (youyouOrderID == 0)
                return false;

            var count = _orderRepository.Count(a => a.Id == youyouOrderID && !string.IsNullOrEmpty(a.Sn));

            return count > 0;
        }

        /// <summary>
        /// 取消YouYou订单
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public bool CancelYouYouOrder(string avisOrderNo)
        {
            if (string.IsNullOrEmpty(avisOrderNo))
            {
                throw new UserFriendlyException("取消YouYou订单需要输入Avis订单号！");
            }

            try
            {
                // 发起老版的取消游友订单请求
                var dicYouYou = new Dictionary<string, string>();
                dicYouYou.Add("note", "系统自动取消，原因：AVIS订单已取消。");
                string youyouUrl = "http://121.40.161.117:8080/order/" + avisOrderNo + "/cancelbythirdno.json?apiKey=test";
                nbHttpClient.PostAsync(youyouUrl, dicYouYou);
            }
            catch (Exception ex)
            {
                this.Logger.Error("调用老版的取消游友订单请求出错了，", ex);
            }

            var dic = new Dictionary<string, string>();
            dic.Add("note", "系统自动取消，原因：AVIS订单已取消。");
            string url = Url_youyou + "/order/" + avisOrderNo + "/cancelbythirdno.json?apiKey=" + Apikey_youyou;
            nbHttpClient.PostAsync(url, dic);

            return true;
        }

        /// <summary>
        /// 查询漫游包Wifi订单的详情信息（通过接口）
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public string GetOrder(string avisOrderNo)
        {
            if (string.IsNullOrEmpty(avisOrderNo))
            {
                throw new UserFriendlyException("获取境外移动WiFi订单需要输入Avis订单号！");
            }

            var result = string.Empty;
            try
            {
                string url = Url_youyou + "/order/" + avisOrderNo + "/安飞士/query.json?apiKey=" + Apikey_youyou;
                result = nbHttpClient.GetAsync(url);
                if (string.IsNullOrEmpty(result))
                {
                    string youyouUrl = "http://121.40.161.117:8080/order/" + avisOrderNo + "/安飞士/query.json?apiKey=test";
                    result = nbHttpClient.GetAsync(url);
                }
            }
            catch (Exception ex)
            {
                this.Logger.Error("调用获取游友订单请求出错了，", ex);
            }

            return result;
        }

        /// <summary>
        /// 获取漫游包Wifi订单的详情信息（本地DB）
        /// </summary>
        /// <param name="avisOrderNo">(必填)AVIS订单号</param>
        /// <returns></returns>
        public YouYouOrder GetDBOrder(string avisOrderNo)
        {
            var order = GetOrderInDBOrCache(avisOrderNo);
            if (order != null && order.YouyouOrderID > 0)
            {
                var youyouOrder = _orderRepository.FirstOrDefault(a => a.Id == order.YouyouOrderID);
                return youyouOrder;
            }

            return null;
        }

        /// <summary>
        /// 获取游友产品（现在修改为漫游包Wifi）
        /// </summary>
        /// <returns></returns>
        public AbroadWiFiProduct GetProducts(string country)
        {
            string url = Url_youyou + "/product/groupbycoop.json?coop=avis&apiKey=" + Apikey_youyou;
            if (!string.IsNullOrEmpty(country))
            {
                url += "&country=" + country;
            }

            var result = nbHttpClient.GetAsync(url);
            if (!string.IsNullOrEmpty(result) && result.ToLower().Contains("discount"))
            {
                var product = JsonConvert.DeserializeObject<AbroadWiFiProduct>(result);
                return product;
            }

            return null;
        }

        /// <summary>
        /// 更改游友订单（现在修改为漫游包Wifi订单）的状态
        /// </summary>
        /// <param name="avisOrderNo"></param>
        /// <param name="youyouNo"></param>
        /// <returns></returns>
        public bool UpdateStatusToCancel(string avisOrderNo, string youyouNo)
        {
            var order = GetOrderInDBOrCache(avisOrderNo);
            if (order != null)
            {
                if (order.IsCancel)
                {
                    CancelYouYouOrder(avisOrderNo);
                }
                else
                {
                    var youyouOrder = _orderRepository.FirstOrDefault(a => a.Id == order.YouyouOrderID);
                    if (youyouOrder != null)
                    {
                        youyouOrder.Sn = youyouNo;
                        youyouOrder.Status = 1;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 新插入游友订单（现在修改为漫游包Wifi订单）
        /// </summary>
        /// <param name="order">Avis订单</param>
        /// <returns></returns>
        public bool SaveOrder(Order order, ThirdOrderModel thirdOrder)
        {
            var youyouOrder = new YouYouOrder
            {
                ProductID = int.Parse(thirdOrder.ProductID),
                Price = decimal.Parse(thirdOrder.Price),
                ProductName = thirdOrder.ProductName,
                AvisNo = order.OrderNo,
                AvisDays = order.RentalLength,
                UserName = order.Surname + order.Firstname,
                Mobile = order.Telephone,
                StartDate = order.PickupDateTime.ToShortDateString(),
                EndDate = order.ReturnDateTime.ToShortDateString(),

                CreateDate = Abp.Timing.Clock.Now,
                ModifyDate = Abp.Timing.Clock.Now,
            };
            var id = _orderRepository.InsertAndGetId(youyouOrder);

            // 更新订单信息
            order.YouyouOrderID = id;
            _avisOrderRepository.UpdateYouyouOrderID(order.OrderNo, id);

            return true;
        }

        /// <summary>
        /// 因为跟IOrderManager有循环引用，故写在这里
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="surname"></param>
        /// <returns></returns>
        private Order GetOrderInDBOrCache(string orderNo)
        {
            var cacheItem = _cacheManager.GetOrderCache().Get(orderNo, f =>
            {
                return _objectMapper.Map<OrderCacheItem>(_avisOrderRepository.GetOrder(orderNo));
            });
            return _objectMapper.Map<Order>(cacheItem);
        }
    }
}
